//
//  discountCouponViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/3/14.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "discountCouponViewController.h"
#import "configddd.h"
#import "UIImageView+WebCache.h"
#import "discountCouponTableViewCell.h"
#import "ToolAboutTime.h"

@interface discountCouponViewController ()<UITableViewDelegate , UITableViewDataSource>

@property(nonatomic , strong)UITableView *discountCouponTableView;
@property(nonatomic , strong)NSMutableArray *dataArr;

@end

@implementation discountCouponViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"优惠券";
    
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(50))];
    cancelBtn.titleLabel.font = get4sFont(13);
    cancelBtn.backgroundColor = getColor(@"f5f5f5");
    [cancelBtn setTitle:@"不使用优惠券" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];
    
    self.discountCouponTableView = [[UITableView alloc]init];
    self.dataArr = [[NSMutableArray alloc]init];
//    self.mark = [[NSString alloc]init];
    [self requestData];
}

#pragma mark - requestData

- (void)requestData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
    NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
    [productParams setValue:uidStr forKey:@"member_id"];
    [productParams setValue:tokenStr forKey:@"token"];
    [[MNetworkHandler sharedInstance]conURL:DiscountCoupon
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       _dataArr = [returnData objectForKey:@"data"];
                                       
                                       [_discountCouponTableView reloadData];
                                       
                                       [hud removeFromSuperview];
                                       
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-2){
                                       
                                       [hud removeFromSuperview];
                                   
                                       [PublicFunction showAlert:nil message:@"没有可用优惠券呦" duration:5.0f];
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

- (void)cancelBtnClick{

    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"no",@"selected", nil];
    NSNotification *notification =[NSNotification notificationWithName:@"money" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - init

- (void)setDiscountCouponTableView:(UITableView *)discountCouponTableView{
    
    _discountCouponTableView = discountCouponTableView;
    _discountCouponTableView.frame = CGRectMake(0, screenScale(50), scrWidth(), scrHeight() - 64 - screenScale(50));
    _discountCouponTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _discountCouponTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _discountCouponTableView.delegate = self;
    _discountCouponTableView.dataSource = self;
    _discountCouponTableView.backgroundColor = getColor(@"f5f5f5");
    [self.view addSubview:_discountCouponTableView];
}

- (void)setDataArr:(NSMutableArray *)dataArr{
    
    _dataArr = dataArr;
}

- (void)setMark:(NSString *)mark{
    
    _mark = mark;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return screenScale(200);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([_mark isEqualToString:_dataArr[indexPath.row][@"id"]]) {
        
        _mark = @"no";
        
        NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"selected",_dataArr[indexPath.row][@"use_vouchers"],@"money", nil];
        NSNotification *notification =[NSNotification notificationWithName:@"money" object:nil userInfo:dict];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }else{
        
        _mark = _dataArr[indexPath.row][@"id"];
        
        NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"selected",_dataArr[indexPath.row][@"use_vouchers"],@"money",_dataArr[indexPath.row][@"id"],@"id", nil];
        NSNotification *notification =[NSNotification notificationWithName:@"money" object:nil userInfo:dict];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView registerClass:[discountCouponTableViewCell class] forCellReuseIdentifier:@"identifier"];
    discountCouponTableViewCell *cell = (discountCouponTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (_dataArr) {
        
        NSString *str1 = @"满";
        NSString *str2 = @"可用";
        NSString *str3 = [str1 stringByAppendingString:[_dataArr[indexPath.row] objectForKey:@"all_vouchers"]];
        
        cell.all_vouchersLable.text = [str3 stringByAppendingString:str2];
        cell.use_vouchersLable.text = [_dataArr[indexPath.row] objectForKey:@"use_vouchers"];
        
        NSTimeInterval time2 =[_dataArr[indexPath.row][@"start_time"] doubleValue];
        NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:time2];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy.MM.dd"];
        NSString *currentTime = [formatter stringFromDate:date2];
        
        cell.startDateLable.text = currentTime;
        
        NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init];
        [formatter1 setDateFormat:@"yyyy.MM.dd"];
        NSString *currentTime1 = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[_dataArr[indexPath.row][@"end_time"] doubleValue]]];
        
        cell.endDateLable.text = currentTime1;
    }
    
    return cell;
}

@end
